package xyz.kongbai121.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import xyz.kongbai121.demo.domain.RespBean;
import xyz.kongbai121.demo.service.ITreeService;
import xyz.kongbai121.demo.util.SensitiveWord;
import xyz.kongbai121.demo.util.UserPowerException;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

/**
 * 树洞处理控制器
 *
 * @author 空白
 */
@RestController
@RequestMapping("/tree")
public class TreeController {

    @Autowired
    private ITreeService service;

    @RequestMapping("/save")
    public RespBean saveTree(String head, String body, String imgPath, String token, Integer classify) {
        //敏感字符处理
        String securityHead = SensitiveWord.getSensitiveWord().filterInfo(head);
        String securityBody = SensitiveWord.getSensitiveWord().filterInfo(body);
        //保存业务
        String msg = service.save(securityHead, securityBody, imgPath, token, classify);
        return new RespBean(true, msg);
    }

    @RequestMapping("/img")
    public Map<String, String> img(@RequestPart MultipartFile file) {
        Map<String, String> map = new HashMap<>();
        //如果有文件
        if (file.getSize() > 0) {
            String fileName = file.getOriginalFilename();
            String serverFileName = "../userdata/" + fileName;
            File co = new File(serverFileName);
            try {
                Files.copy(file.getInputStream(), co.toPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(fileName);
            map.put("serverFileName", fileName);
        }
        return map;
    }

    @RequestMapping("/list")
    public RespBean listTree(Integer classify) {
        if (classify != null && classify == 0) classify = null;
        return new RespBean(true, service.list(classify));
    }

    @RequestMapping("/get")
    public RespBean getTree(Long id) {
        return new RespBean(true, service.get(id));
    }

    @RequestMapping("/delete")
    public RespBean deleteArticle(Long id, String token) {
        String msg = service.delete(id, token);
        return new RespBean(true, msg);
    }

}
